package com.yiyuan.common.search;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class IndexManager {

	public static final File INDEX_DIR = new File(Constants.INDEX_DIR_PATH);

	// 实时添加索引
	public static void add(DocObj docObj) throws Exception {

		Date start = new Date();
		IndexWriter writer = null;
		try {
			Analyzer analyzer = new IKAnalyzer();
			writer = new IndexWriter(FSDirectory.open(INDEX_DIR),analyzer, false,
					IndexWriter.MaxFieldLength.LIMITED);
			writer.addDocument(FileDocument.Document(docObj));
			System.out.println("Optimizing...");
			writer.optimize();			

			Date end = new Date();
			System.out.println(end.getTime() - start.getTime()
					+ " total milliseconds");

		} catch (IOException e) {
			System.out.println(" caught a " + e.getClass()
					+ "\n with message: " + e.getMessage());
		} finally {
			if (writer != null) {
				writer.commit();
				writer.close();
			}
		}
	}

	// 根据文件路径删除对应的索引
	public static void delete(String docId) {
		if (docId == null) {
			System.out.println("文件已经删除，或不存在！");
		}
		try {
			Directory directory = FSDirectory.open(INDEX_DIR);
			IndexReader reader = IndexReader.open(directory, false);

			Term term = new Term("docId", docId);
			int deleted = reader.deleteDocuments(term);

			System.out.println("deleted " + deleted + " documents containing "
					+ term);

			reader.close();
			directory.close();

		} catch (Exception e) {
			System.out.println(" caught a " + e.getClass()
					+ "\n with message: " + e.getMessage());
		}
	}

}
